<template>
  <el-dialog v-model="visible" :width="'80%'" :title="'新增'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <template v-slot:default>
      <div>
        <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
          <el-form-item label="用户呢称">
            <el-input v-model="state.dataForm.username" placeholder="请输入用户名呢称" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户账号">
            <el-input v-model="state.dataForm.mobile" placeholder="请输入用户账号" clearable></el-input>
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input v-model="state.dataForm.projectName" placeholder="请输入项目名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="state.getDataList()">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="state.dataListLoading" :data="state.dataList"
                  @selection-change="state.dataListSelectionChangeHandle"
                  style="width: 100%"
                  ref="tableRef"
                  row-key="id"
                  :selectable="isRow"
        >
          <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
          <el-table-column prop="username" label="用户名呢称" header-align="center" align="center"></el-table-column>
          <el-table-column prop="mobile" label="用户账号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="userrole" label="用户角色" header-align="center" align="center">
            <template v-slot="scope">
              <el-tag v-if="scope.row.userrole === 1" size="small" type="danger">施工人员</el-tag>
              <el-tag v-if="scope.row.userrole === 2" size="small" type="info">施工负责人</el-tag>
              <el-tag v-if="scope.row.userrole === 3" size="small" type="success">管理人员</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="listIds" label="参与项目" header-align="center" align="center">
            <template v-slot="scope">
              <template v-for="item in scope.row.listIds">
                <template  v-if="null != item" >
                  <el-tag size="small" type="info">{{ item.name }}</el-tag>
                </template>
              </template>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
                       :total="state.total" layout="total, sizes, prev, pager, next, jumper"
                       @size-change="state.pageSizeChangeHandle"
                       @current-change="state.pageCurrentChangeHandle"></el-pagination>
      </div>
    </template>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import {reactive, ref, toRefs, nextTick} from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router";
const router = useRouter();

const emit = defineEmits(["refreshDataList"]);
const view = reactive({
  getDataListURL: "/sysapp/user/page",
  getDataListIsPage: true,
  deleteURL: "/sys/usermange",
  deleteIsBatch: true,
  exportURL: "/sys/usermange/export",
  proUserData: "",
  dataForm: {
    username: "", mobile: "", projectName: "",
  },
  projectId:"",
  dataListSelectionsSub:[],
  dataListSelectionsSubRole:[],

});
const state = reactive({...useView(view), ...toRefs(view)});
const selectionList = ref([])
const visible = ref(false);
const tableRef = ref();

const init = (id?: string) => {
  state.dataListSelections=[];
  state.dataListSelectionsSub=[];
  state.dataListSelectionsSubRole=[];
  if(""==id){
    ElMessage.error({ message: '请重新选择项目',duration: 500,
      onClose: () => {
        router.replace("/sysproject/project");
      }
    });
    return
  }
  state.projectId=id;
  visible.value = true;
  state.dataForm = {
    username: "", mobile: "", projectName: "",
  }
  // state.dataListSelectionChangeHandle()
  nextTick(() => {
    tableRef.value.clearSelection
    baseService.get("/sysapp/user/getUserListProStr", {"projectId": id}).then((res) => {
      view.proUserData = res.data;
      state.getDataList();
    })
  })
};

//获取数据
state.getDataList = () => {
  if (!state.getDataListURL) {
    return;
  }
  state.dataListLoading = true;
  baseService
    .get(state.getDataListURL, {
      order: state.order,
      orderField: state.orderField,
      page: state.getDataListIsPage ? state.page : null,
      limit: state.getDataListIsPage ? state.limit : null,
      ...state.dataForm,
      "type":1
    })
    .then((res) => {
      state.dataListLoading = false;
      state.dataList = state.getDataListIsPage ? res.data.list : res.data;
      state.pageData = state.getDataListIsPage ? res.data.data : res.data;
      state.total = state.getDataListIsPage ? res.data.total : 0;
      tableRef.value.clearSelection
      state.dataList.forEach(row => {
        nextTick(() => {
          if (view.proUserData.includes(row.id)) {
            tableRef.value.toggleRowSelection(row, true);
          }
          //tableRef.value.toggleAllSelection =true
        })
      })
    })
    .catch(() => {
      state.dataListLoading = false;
    });
}
state.pageSizeChangeHandle=(val: number)=> {
  state.page = 1;
  state.limit = val;
  state.getDataList();
}
state.pageCurrentChangeHandle=(val: number)=> {
  state.page = val;
  state.getDataList();
}
//禁止用户编辑
const okLists = ref(view.proUserData.split(","))
const isRow=(row:any,rowIndex:any)=>{
  return !okLists.value.includes(row.id)
}


const dataFormSubmitHandle=()=>{
  debugger
  console.log(state.dataListSelections)
  //判断当前的选中数据中是否含有已经存在的勾选数据有就剔出
  state.dataListSelections?.forEach(item =>{
      state.dataListSelectionsSub.push(item.id)
      state.dataListSelectionsSubRole.push(item.userrole);
  })
  if(state.dataListSelectionsSub.length ==0){
    ElMessage.error({
      message: '请勾选您要添加的数据',
      duration: 1000,
      onClose: () => {
      }
    });
    return
  }
  console.log(state.dataListSelectionsSub)
  console.log(state.dataListSelectionsSub.join(","))
  baseService.put("/sysapp/user/saveUserPro",
    {"projectId":state.projectId ,
            "userIds":state.dataListSelectionsSub.join(","),
            "roles":state.dataListSelectionsSubRole.join(","),
           }
  ).then((res) => {
    ElMessage.success({
      message: '成功',
      duration: 600,
      onClose: () => {
        visible.value = false;
        emit("refreshDataList");
      }
    });
  })
}
defineExpose({
  init
});
</script>
